///
/// 单选框组件
/// 参照Element UI的Radio控件实现

// ignore_for_file: dangling_library_doc_comments

import 'package:flutter/material.dart';
import '../../core/elegance_theme.dart';

/// 单选框大小类型枚举
enum ERadioSize {
  /// 小型单选框
  small,
  
  /// 普通大小单选框
  normal,
}

/// ERadio组件
class ERadio<T> extends StatefulWidget {
  /// 创建ERadio组件
  const ERadio({
    super.key,
    required this.value,
    required this.groupValue,
    this.onChanged,
    this.label,
    this.size = ERadioSize.normal,
    this.disabled = false,
    this.textStyle,
  });

  /// 当前单选框的值
  final T value;
  
  /// 单选组当前的值
  final T groupValue;
  
  /// 选中状态变更回调
  final ValueChanged<T>? onChanged;
  
  /// 单选框旁边的文本标签
  final String? label;
  
  /// 单选框大小
  final ERadioSize size;
  
  /// 是否禁用
  final bool disabled;
  
  /// 自定义文本样式
  final TextStyle? textStyle;

  @override
  State<ERadio<T>> createState() => _ERadioState<T>();
}

class _ERadioState<T> extends State<ERadio<T>> {
  /// 是否处于选中状态
  bool get _isSelected => widget.value == widget.groupValue;
  
  /// 是否处于悬浮状态
  bool _isHovered = false;
  
  /// 处理点击事件
  void _handleTap() {
    if (!widget.disabled && widget.onChanged != null) {
      widget.onChanged!(widget.value);
    }
  }

  /// 获取单选框直径
  double _getRadioDiameter() {
    switch (widget.size) {
      case ERadioSize.small:
        return 16.0;
      case ERadioSize.normal:
      default:
        return 20.0;
    }
  }
  
  /// 获取单选框内部圆点直径
  double _getInnerDotDiameter() {
    switch (widget.size) {
      case ERadioSize.small:
        return 8.0;
      case ERadioSize.normal:
      default:
        return 10.0;
    }
  }
  
  /// 获取边框宽度
  double _getBorderWidth() {
    switch (widget.size) {
      case ERadioSize.small:
        return 1.5;
      case ERadioSize.normal:
      default:
        return 2.0;
    }
  }
  
  /// 获取文本字体大小
  double _getTextFontSize() {
    switch (widget.size) {
      case ERadioSize.small:
        return 14.0;
      case ERadioSize.normal:
      default:
        return 16.0;
    }
  }
  
  /// 获取单选框颜色
  Color _getRadioColor(EleganceThemeData theme) {
    if (widget.disabled) {
      return theme.textPlaceholderColor;
    }
    
    if (_isSelected) {
      return theme.primaryColor;
    }
    
    return _isHovered ? theme.primaryColor.withOpacity(0.6) : theme.borderColor;
  }
  
  /// 获取文本颜色
  Color _getTextColor(EleganceThemeData theme) {
    if (widget.disabled) {
      return theme.textPlaceholderColor;
    }
    
    return widget.textStyle?.color ?? theme.textPrimaryColor;
  }

  @override
  Widget build(BuildContext context) {
    final theme = EleganceTheme.of(context);
    final diameter = _getRadioDiameter();
    final innerDotDiameter = _getInnerDotDiameter();
    final borderWidth = _getBorderWidth();
    final textFontSize = _getTextFontSize();
    final radioColor = _getRadioColor(theme);
    final textColor = _getTextColor(theme);
    
    // 构建单选框核心部分
    final radioWidget = Container(
      width: diameter,
      height: diameter,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        border: Border.all(
          color: radioColor,
          width: borderWidth,
        ),
        color: widget.disabled ? Colors.transparent : 
               _isSelected ? radioColor.withOpacity(0.05) : Colors.transparent,
      ),
      child: _isSelected
          ? Center(
              child: Container(
                width: innerDotDiameter,
                height: innerDotDiameter,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: radioColor,
                ),
              ),
            )
          : null,
    );
    
    // 构建完整的单选框组件（包含可选的文本标签）
    Widget child;
    if (widget.label != null) {
      child = Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          radioWidget,
          const SizedBox(width: 8.0),
          Text(
            widget.label!,
            style: TextStyle(
              fontSize: widget.textStyle?.fontSize ?? textFontSize,
              color: textColor,
              fontWeight: widget.textStyle?.fontWeight ?? FontWeight.normal,
            ),
          ),
        ],
      );
    } else {
      child = radioWidget;
    }
    
    // 添加事件处理和状态
    return MouseRegion(
      onEnter: (_) {
        if (!widget.disabled) {
          setState(() {
            _isHovered = true;
          });
        }
      },
      onExit: (_) {
        if (!widget.disabled) {
          setState(() {
            _isHovered = false;
          });
        }
      },
      cursor: widget.disabled ? MouseCursor.defer : SystemMouseCursors.click,
      child: GestureDetector(
        onTap: _handleTap,
        child: child,
      ),
    );
  }
}

/// ERadioGroup组件 - 用于管理一组单选框
class ERadioGroup<T> extends StatefulWidget {
  /// 创建ERadioGroup组件
  const ERadioGroup({
    super.key,
    this.value,
    this.onChanged,
    this.children,
    this.disabled = false,
    this.direction = Axis.vertical,
  });
  
  /// 当前选中的值
  final T? value;
  
  /// 值变更回调
  final ValueChanged<T>? onChanged;
  
  /// 子组件（通常是多个ERadio）
  final List<Widget>? children;
  
  /// 是否禁用整个单选组
  final bool disabled;
  
  /// 子组件排列方向
  final Axis direction;
  
  @override
  State<ERadioGroup<T>> createState() => _ERadioGroupState<T>();
}

class _ERadioGroupState<T> extends State<ERadioGroup<T>> {
  @override
  Widget build(BuildContext context) {
    // 处理子组件，将单选框的值和事件处理绑定到单选组
    Widget child;
    if (widget.direction == Axis.vertical) {
      child = Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: widget.children ?? [],
      );
    } else {
      child = Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: widget.children ?? [],
      );
    }
    
    // 提供RadioGroup的InheritedWidget给子组件
    return _ERadioGroupProvider<T>(
      value: widget.value,
      onChanged: widget.onChanged,
      disabled: widget.disabled,
      child: child,
    );
  }
}

/// ERadioGroup的InheritedWidget实现，用于向下传递值和回调
class _ERadioGroupProvider<T> extends InheritedWidget {
  const _ERadioGroupProvider({
    required super.child,
    required this.value,
    required this.onChanged,
    required this.disabled,
  });
  
  final T? value;
  final ValueChanged<T>? onChanged;
  final bool disabled;
  
  @override
  bool updateShouldNotify(_ERadioGroupProvider<T> oldWidget) {
    return value != oldWidget.value || 
           onChanged != oldWidget.onChanged || 
           disabled != oldWidget.disabled;
  }
  
  // 静态方法，用于子组件获取RadioGroup的值和回调
  static _ERadioGroupProvider<T>? of<T>(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<_ERadioGroupProvider<T>>();
  }
}